<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库单号" prop="receiptNo">
        <el-input
          v-model="queryParams.receiptNo"
          placeholder="请输入入库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库类型" prop="receiptType">
        <el-select v-model="queryParams.receiptType" placeholder="请选择入库类型" clearable>
          <el-option
            v-for="dict in dict.type.wms_receipt_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="receiptStatus">
        <el-select v-model="queryParams.receiptStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_receipt_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:receipt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:receipt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:receipt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:receipt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单号" align="center" prop="receiptNo" />
      <el-table-column label="入库类型" align="center" prop="receiptType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_receipt_type" :value="scope.row.receiptType"/>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="供应商/客户" align="center" prop="supplierName" />
      <el-table-column label="计划入库时间" align="center" prop="plannedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.plannedTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="receiptStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_receipt_status" :value="scope.row.receiptStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['wms:receipt:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:receipt:edit']"
            v-if="scope.row.receiptStatus === '0'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:receipt:remove']"
            v-if="scope.row.receiptStatus === '0'"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['wms:receipt:audit']"
            v-if="scope.row.receiptStatus === '0'"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleExecute(scope.row)"
            v-hasPermi="['wms:receipt:execute']"
            v-if="scope.row.receiptStatus === '1'"
          >执行入库</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库类型" prop="receiptType">
              <el-select v-model="form.receiptType" placeholder="请选择入库类型">
                <el-option
                  v-for="dict in dict.type.wms_receipt_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" @change="handleWarehouseChange">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId" v-if="form.receiptType === '1'">
              <el-select v-model="form.supplierId" placeholder="请选择供应商">
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.supplierId"
                  :label="item.supplierName"
                  :value="item.supplierId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户" prop="customerId" v-if="form.receiptType === '2'">
              <el-select v-model="form.customerId" placeholder="请选择客户">
                <el-option
                  v-for="item in customerOptions"
                  :key="item.customerId"
                  :label="item.customerName"
                  :value="item.customerId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="调出仓库" prop="fromWarehouseId" v-if="form.receiptType === '3'">
              <el-select v-model="form.fromWarehouseId" placeholder="请选择调出仓库">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源单号" prop="sourceOrderNo">
              <el-input v-model="form.sourceOrderNo" placeholder="请输入来源单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划入库时间" prop="plannedTime">
              <el-date-picker
                v-model="form.plannedTime"
                type="datetime"
                placeholder="选择计划入库时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">入库明细</el-divider>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDetail">添加明细</el-button>
            <el-table :data="form.details" style="margin-top: 10px;">
              <el-table-column label="序号" type="index" width="55" align="center" />
              <el-table-column label="物料" prop="materialName" min-width="120">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.materialId" placeholder="请选择物料" @change="(val) => handleMaterialChange(val, scope.$index)">
                    <el-option
                      v-for="item in materialOptions"
                      :key="item.materialId"
                      :label="item.materialName"
                      :value="item.materialId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="计划数量" prop="plannedQuantity" width="120">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.plannedQuantity" :min="1" :precision="2" />
                </template>
              </el-table-column>
              <el-table-column label="库区" prop="areaName" width="120">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.areaId" placeholder="请选择库区" @change="(val) => handleAreaChange(val, scope.$index)">
                    <el-option
                      v-for="item in areaOptions"
                      :key="item.areaId"
                      :label="item.areaName"
                      :value="item.areaId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="库位" prop="locationName" width="120">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.locationId" placeholder="请选择库位">
                    <el-option
                      v-for="item in locationOptions[scope.$index] || []"
                      :key="item.locationId"
                      :label="item.locationName"
                      :value="item.locationId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="批次号" prop="batchNo" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.batchNo" placeholder="请输入批次号" />
                </template>
              </el-table-column>
              <el-table-column label="生产日期" prop="productionDate" width="120">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.productionDate"
                    type="date"
                    placeholder="选择生产日期"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="过期日期" prop="expiryDate" width="120">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.expiryDate"
                    type="date"
                    placeholder="选择过期日期"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="80">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteDetail(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 入库单查看对话框 -->
    <el-dialog title="入库单详情" :visible.sync="viewOpen" width="780px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="入库单号">{{ viewForm.receiptNo }}</el-descriptions-item>
        <el-descriptions-item label="入库类型">
          <dict-tag :options="dict.type.wms_receipt_type" :value="viewForm.receiptType"/>
        </el-descriptions-item>
        <el-descriptions-item label="仓库">{{ viewForm.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="供应商/客户">{{ viewForm.supplierName || viewForm.customerName }}</el-descriptions-item>
        <el-descriptions-item label="来源单号">{{ viewForm.sourceOrderNo }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.wms_receipt_status" :value="viewForm.receiptStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="计划入库时间">{{ parseTime(viewForm.plannedTime) }}</el-descriptions-item>
        <el-descriptions-item label="实际入库时间">{{ parseTime(viewForm.actualTime) }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ viewForm.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewForm.remark }}</el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="center">入库明细</el-divider>
      <el-table :data="viewForm.details">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="物料名称" prop="materialName" min-width="120" />
        <el-table-column label="物料编码" prop="materialCode" min-width="100" />
        <el-table-column label="计划数量" prop="plannedQuantity" width="100" />
        <el-table-column label="实际数量" prop="actualQuantity" width="100" />
        <el-table-column label="库区" prop="areaName" width="120" />
        <el-table-column label="库位" prop="locationName" width="120" />
        <el-table-column label="批次号" prop="batchNo" width="120" />
        <el-table-column label="生产日期" prop="productionDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="过期日期" prop="expiryDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 入库单审核对话框 -->
    <el-dialog title="入库单审核" :visible.sync="auditOpen" width="500px" append-to-body>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="'1'">通过</el-radio>
            <el-radio :label="'2'">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComment">
          <el-input v-model="auditForm.auditComment" type="textarea" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAudit">确 定</el-button>
        <el-button @click="auditOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 执行入库对话框 -->
    <el-dialog title="执行入库" :visible.sync="executeOpen" width="780px" append-to-body>
      <el-form ref="executeForm" :model="executeForm" label-width="100px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="入库单号">{{ executeForm.receiptNo }}</el-descriptions-item>
          <el-descriptions-item label="入库类型">
            <dict-tag :options="dict.type.wms_receipt_type" :value="executeForm.receiptType"/>
          </el-descriptions-item>
          <el-descriptions-item label="仓库">{{ executeForm.warehouseName }}</el-descriptions-item>
          <el-descriptions-item label="供应商/客户">{{ executeForm.supplierName || executeForm.customerName }}</el-descriptions-item>
        </el-descriptions>
        <el-divider content-position="center">入库明细</el-divider>
        <el-table :data="executeForm.details">
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="物料名称" prop="materialName" min-width="120" />
          <el-table-column label="物料编码" prop="materialCode" min-width="100" />
          <el-table-column label="计划数量" prop="plannedQuantity" width="100" />
          <el-table-column label="实际数量" width="120">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.actualQuantity" :min="0" :max="scope.row.plannedQuantity" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column label="库区" width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.areaId" placeholder="请选择库区" @change="(val) => handleExecuteAreaChange(val, scope.$index)">
                <el-option
                  v-for="item in areaOptions"
                  :key="item.areaId"
                  :label="item.areaName"
                  :value="item.areaId"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="库位" width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.locationId" placeholder="请选择库位">
                <el-option
                  v-for="item in executeLocationOptions[scope.$index] || []"
                  :key="item.locationId"
                  :label="item.locationName"
                  :value="item.locationId"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="批次号" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchNo" placeholder="请输入批次号" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExecute">确 定</el-button>
        <el-button @click="executeOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReceipt, getReceipt, delReceipt, addReceipt, updateReceipt, auditReceipt, executeReceipt, getReceiptDetails } from "@/api/wms/receipt";
import { listWarehouse } from "@/api/wms/warehouse";
import { listArea } from "@/api/wms/area";
import { listLocation } from "@/api/wms/location";
import { listMaterial } from "@/api/wms/material";
import { listSupplier } from "@/api/wms/supplier";
import { listCustomer } from "@/api/wms/customer";

export default {
  name: "Receipt",
  dicts: ['wms_receipt_type', 'wms_receipt_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库单表格数据
      receiptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewOpen: false,
      // 是否显示审核弹出层
      auditOpen: false,
      // 是否显示执行入库弹出层
      executeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptNo: null,
        receiptType: null,
        receiptStatus: null
      },
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {
        receiptId: null,
        receiptNo: null,
        receiptType: "1", // 默认设置为采购入库
        warehouseId: null,
        supplierId: null,
        customerId: null,
        fromWarehouseId: null,
        sourceOrderNo: null,
        plannedTime: null,
        receiptStatus: "0",
        remark: null,
        details: []
      },
      // 查看表单参数
      viewForm: {
        receiptId: null,
        receiptNo: null,
        receiptType: null,
        warehouseName: null,
        supplierName: null,
        customerName: null,
        sourceOrderNo: null,
        plannedTime: null,
        actualTime: null,
        receiptStatus: null,
        createBy: null,
        createTime: null,
        remark: null,
        details: []
      },
      // 审核表单参数
      auditForm: {
        receiptId: null,
        auditStatus: "1",
        auditComment: null
      },
      // 执行入库表单参数
      executeForm: {
        receiptId: null,
        receiptNo: null,
        receiptType: null,
        warehouseName: null,
        supplierName: null,
        customerName: null,
        details: []
      },
      // 表单校验
      rules: {
        receiptType: [
          { required: true, message: "入库类型不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        customerId: [
          { required: true, message: "客户不能为空", trigger: "change" }
        ],
        fromWarehouseId: [
          { required: true, message: "调出仓库不能为空", trigger: "change" }
        ],
        plannedTime: [
          { required: true, message: "计划入库时间不能为空", trigger: "blur" }
        ]
      },
      // 审核表单校验
      auditRules: {
        auditStatus: [
          { required: true, message: "审核结果不能为空", trigger: "change" }
        ],
        auditComment: [
          { required: true, message: "审核意见不能为空", trigger: "blur" }
        ]
      },
      // 仓库选项
      warehouseOptions: [],
      // 供应商选项
      supplierOptions: [],
      // 客户选项
      customerOptions: [],
      // 物料选项
      materialOptions: [],
      // 库区选项
      areaOptions: [],
      // 库位选项
      locationOptions: [],
      // 执行入库库位选项
      executeLocationOptions: []
    };
  },
  created() {
    this.getList();
    this.getWarehouseOptions();
    this.getSupplierOptions();
    this.getCustomerOptions();
    this.getMaterialOptions();
  },
  methods: {
    /** 查询入库单列表 */
    getList() {
      this.loading = true;
      listReceipt(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.receiptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取仓库选项 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        this.warehouseOptions = response.rows;
      });
    },
    /** 获取供应商选项 */
    getSupplierOptions() {
      listSupplier().then(response => {
        this.supplierOptions = response.rows;
      });
    },
    /** 获取客户选项 */
    getCustomerOptions() {
      listCustomer().then(response => {
        this.customerOptions = response.rows;
      });
    },
    /** 获取物料选项 */
    getMaterialOptions() {
      listMaterial().then(response => {
        this.materialOptions = response.rows;
      });
    },
    /** 获取库区选项 */
    getAreaOptions(warehouseId) {
      listArea({ warehouseId: warehouseId }).then(response => {
        this.areaOptions = response.rows;
      });
    },
    /** 获取库位选项 */
    getLocationOptions(areaId, index) {
      listLocation({ areaId: areaId }).then(response => {
        this.$set(this.locationOptions, index, response.rows);
      });
    },
    // 仓库选择事件
    handleWarehouseChange(warehouseId) {
      this.form.details = [];
      this.getAreaOptions(warehouseId);
    },
    // 库区选择事件
    handleAreaChange(areaId, index) {
      this.getLocationOptions(areaId, index);
    },
    // 物料选择事件
    handleMaterialChange(materialId, index) {
      const material = this.materialOptions.find(item => item.materialId === materialId);
      if (material) {
        this.form.details[index].materialName = material.materialName;
        this.form.details[index].materialCode = material.materialCode;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        receiptId: null,
        receiptNo: null,
        receiptType: "1", // 默认设置为采购入库
        warehouseId: null,
        supplierId: null,
        customerId: null,
        fromWarehouseId: null,
        sourceOrderNo: null,
        plannedTime: null,
        receiptStatus: "0",
        remark: null,
        details: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.receiptId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const receiptId = row.receiptId || this.ids[0];
      getReceipt(receiptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库单";
        
        // 加载库区和库位数据
        this.getAreaOptions(this.form.warehouseId);
        this.form.details.forEach((item, index) => {
          if (item.areaId) {
            this.getLocationOptions(item.areaId, index);
          }
        });
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      getReceipt(row.receiptId).then(response => {
        this.viewForm = response.data;
        this.viewOpen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.details.length === 0) {
            this.$modal.msgWarning("请添加入库明细");
            return;
          }
          
          if (this.form.receiptId != null) {
            updateReceipt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReceipt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const receiptIds = row.receiptId || this.ids;
      this.$modal.confirm('是否确认删除入库单编号为"' + receiptIds + '"的数据项?').then(function() {
        return delReceipt(receiptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/receipt/export', {
        ...this.queryParams
      }, `receipt_${new Date().getTime()}.xlsx`);
    },
    /** 添加明细 */
    handleAddDetail() {
      this.form.details.push({
        materialId: null,
        materialName: null,
        materialCode: null,
        plannedQuantity: 1,
        areaId: null,
        areaName: null,
        locationId: null,
        locationName: null,
        batchNo: null,
        productionDate: null,
        expiryDate: null
      });
    },
    /** 删除明细 */
    handleDeleteDetail(index) {
      this.form.details.splice(index, 1);
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.auditForm = {
        receiptId: row.receiptId,
        auditStatus: "1",
        auditComment: null
      };
      this.auditOpen = true;
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          auditReceipt(this.auditForm).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.auditOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 执行入库操作 */
    handleExecute(row) {
      getReceipt(row.receiptId).then(response => {
        this.executeForm = {
          receiptId: response.data.receiptId,
          receiptNo: response.data.receiptNo,
          receiptType: response.data.receiptType,
          warehouseName: response.data.warehouseName,
          supplierName: response.data.supplierName,
          customerName: response.data.customerName,
          details: response.data.details.map(item => {
            return {
              ...item,
              actualQuantity: item.plannedQuantity // 默认实际数量等于计划数量
            };
          })
        };
        
        // 加载库区和库位数据
        this.getAreaOptions(response.data.warehouseId);
        this.executeForm.details.forEach((item, index) => {
          if (item.areaId) {
            this.getExecuteLocationOptions(item.areaId, index);
          }
        });
        
        this.executeOpen = true;
      });
    },
    
    /** 获取执行入库的库位选项 */
    getExecuteLocationOptions(areaId, index) {
      listLocation({ areaId: areaId }).then(response => {
        this.$set(this.executeLocationOptions, index, response.rows);
      });
    },
    
    /** 执行入库库区选择事件 */
    handleExecuteAreaChange(areaId, index) {
      this.getExecuteLocationOptions(areaId, index);
    },
    
    /** 提交执行入库 */
    submitExecute() {
      // 验证数据
      let valid = true;
      this.executeForm.details.forEach(item => {
        if (!item.areaId || !item.locationId) {
          this.$modal.msgWarning("请选择库区和库位");
          valid = false;
          return false;
        }
        if (item.actualQuantity <= 0) {
          this.$modal.msgWarning("实际数量必须大于0");
          valid = false;
          return false;
        }
      });
      
      if (!valid) {
        return;
      }
      
      executeReceipt(this.executeForm.receiptId, this.executeForm.details).then(() => {
        this.$modal.msgSuccess("入库执行成功");
        this.executeOpen = false;
        this.getList();
      });
    }
  }
};
</script>